package org.kyw.basic.controller;

import org.kyw.basic.util.AjaxResult;
import org.kyw.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 分布式文件存储系统接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    //上传文件
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(required = true, value = "file")MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            String result = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(result);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试");
        }
    }

    //删除文件
    @DeleteMapping
    public AjaxResult remove(@RequestParam(required = true, value = "path")String path) {
        try {
            String pathTmp = path.substring(1);
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试");
        }
    }

}
